using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VOL.Entity.DomainModels;
using VOL.demo.IRepositories;
using VOL.Core.BaseProvider;
using VOL.Core.Utilities;
using VOL.Core.Extensions;
using System.Linq;

namespace VOL.demo.Services
{
    public partial class productinformationmodelService
    {
        /// <summary>
        /// 获取货品信息下拉选项
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>货品信息列表</returns>
        public async Task<(List<productinformationmodel> Data, int TotalCount)> GetProductOptionsAsync(
            string keyword = null, 
            int pageIndex = 1, 
            int pageSize = 10)
        {
            return await repository.GetProductOptionsAsync(keyword, pageIndex, pageSize);
        }

        /// <summary>
        /// 根据货品ID获取货品信息
        /// </summary>
        /// <param name="productId">货品ID</param>
        /// <returns>货品信息</returns>
        public async Task<productinformationmodel> GetProductByIdAsync(long productId)
        {
            return await repository.GetProductByIdAsync(productId);
        }

        /// <summary>
        /// 根据货品ID列表批量获取货品信息
        /// </summary>
        /// <param name="productIds">货品ID列表</param>
        /// <returns>货品信息列表</returns>
        public async Task<List<productinformationmodel>> GetProductsByIdsAsync(List<long> productIds)
        {
            return await repository.GetProductsByIdsAsync(productIds);
        }

        /// <summary>
        /// 获取货品类型级联数据
        /// </summary>
        /// <returns></returns>
        public object GetProductTypeCascade()
        {
            // TODO: 实现获取货品类型级联数据的逻辑
            return new { success = true, data = new List<object>() };
        }

        /// <summary>
        /// 生成条码
        /// </summary>
        /// <param name="goodsId">货品ID</param>
        /// <param name="unitId">单位ID</param>
        /// <returns></returns>
        public string GenerateBarcode(long goodsId, long unitId)
        {
            // TODO: 实现生成条码的逻辑
            return $"{goodsId}_{unitId}_{DateTime.Now:yyyyMMddHHmmss}";
        }

        /// <summary>
        /// 添加货品及详细信息
        /// </summary>
        /// <param name="productInfo">货品信息</param>
        /// <param name="unitRelations">单位关系</param>
        /// <param name="inventoryList">库存列表</param>
        /// <param name="imageList">图片列表</param>
        /// <returns></returns>
        public WebResponseContent AddProductWithDetails(
            productinformationmodel productInfo,
            List<GoodsUnitRelationModel> unitRelations,
            List<InventoryModel> inventoryList,
            List<GoodsImageModel> imageList)
        {
            // TODO: 实现添加货品及详细信息的逻辑
            return new WebResponseContent(true);
        }

        /// <summary>
        /// 添加新产品
        /// </summary>
        /// <param name="product">产品信息</param>
        /// <returns>添加结果</returns>
        public async Task<WebResponseContent> AddProductAsync(productinformationmodel product)
        {
            WebResponseContent response = WebResponseContent.Instance;

            if (product == null)
            {
                return response.Error("产品信息不能为空");
            }

            // 验证产品编号
            if (string.IsNullOrEmpty(product.goodsCode))
            {
                return response.Error("产品编号不能为空");
            }

            // 验证产品名称
            if (string.IsNullOrEmpty(product.goodsName))
            {
                return response.Error("产品名称不能为空");
            }

            // 检查产品编号是否已存在
            if (await repository.IsProductCodeExistsAsync(product.goodsCode))
            {
                return response.Error("产品编号已存在");
            }

            // 设置默认值
            product.CreateDate = DateTime.Now;
            product.IsDel = 0; // 0 表示未删除

            // 添加产品
            bool result = await repository.AddProductAsync(product);
            if (!result)
            {
                return response.Error("添加产品失败");
            }

            return response.OK("添加产品成功", product);
        }

        /// <summary>
        /// 检查产品编号是否已存在
        /// </summary>
        /// <param name="goodsCode">产品编号</param>
        /// <returns>存在返回true，不存在返回false</returns>
        public async Task<bool> IsProductCodeExistsAsync(string goodsCode)
        {
            return await repository.IsProductCodeExistsAsync(goodsCode);
        }

        /// <summary>
        /// 分页查询货品详细信息（包含货品类型、供应商、客户名称）
        /// </summary>
        /// <param name="request">查询请求参数</param>
        /// <returns>分页查询结果</returns>
        public async Task<ProductQueryResult> GetProductsWithDetailsAsync(ProductQueryRequest request)
        {
            var result = new ProductQueryResult();
            
            try
            {
                // 参数验证
                if (request == null)
                {
                    result.Success = false;
                    result.Message = "查询参数不能为空";
                    return result;
                }

                if (request.PageIndex < 1) request.PageIndex = 1;
                if (request.PageSize < 1) request.PageSize = 20;
                if (request.PageSize > 100) request.PageSize = 100; // 限制最大页面大小

                // 使用SqlSugar进行多表联查
                var queryable = repository.DbContext.Queryable<productinformationmodel>()
                    .LeftJoin<producttypemodel>((p, pt) => p.productTypeId == pt.id)
                    .LeftJoin<suppliermodel>((p, pt, s) => p.supplierId == s.Id)
                    .LeftJoin<customermodel>((p, pt, s, c) => p.userId == c.Id)
                    .Where((p, pt, s, c) => p.IsDel == 0); // 只查询未删除的记录

                // 添加搜索条件
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    queryable = queryable.Where((p, pt, s, c) => 
                        p.goodsName.Contains(request.Keyword) || 
                        p.goodsCode.Contains(request.Keyword));
                }

                if (request.ProductTypeId.HasValue)
                {
                    queryable = queryable.Where((p, pt, s, c) => p.productTypeId == request.ProductTypeId.Value);
                }

                if (request.SupplierId.HasValue)
                {
                    queryable = queryable.Where((p, pt, s, c) => p.supplierId == request.SupplierId.Value);
                }

                if (request.UserId.HasValue)
                {
                    queryable = queryable.Where((p, pt, s, c) => p.userId == request.UserId.Value);
                }

                if (request.Status.HasValue)
                {
                    queryable = queryable.Where((p, pt, s, c) => p.status == request.Status.Value);
                }

                // 添加排序
                switch (request.OrderBy?.ToLower())
                {
                    case "goodsname":
                        queryable = request.OrderDirection?.ToLower() == "asc" 
                            ? queryable.OrderBy((p, pt, s, c) => p.goodsName)
                            : queryable.OrderByDescending((p, pt, s, c) => p.goodsName);
                        break;
                    case "goodscode":
                        queryable = request.OrderDirection?.ToLower() == "asc" 
                            ? queryable.OrderBy((p, pt, s, c) => p.goodsCode)
                            : queryable.OrderByDescending((p, pt, s, c) => p.goodsCode);
                        break;
                    case "purchaseprice":
                        queryable = request.OrderDirection?.ToLower() == "asc" 
                            ? queryable.OrderBy((p, pt, s, c) => p.purchasePrice)
                            : queryable.OrderByDescending((p, pt, s, c) => p.purchasePrice);
                        break;
                    case "saleprice":
                        queryable = request.OrderDirection?.ToLower() == "asc" 
                            ? queryable.OrderBy((p, pt, s, c) => p.salePrice)
                            : queryable.OrderByDescending((p, pt, s, c) => p.salePrice);
                        break;
                    case "currentinventory":
                        queryable = request.OrderDirection?.ToLower() == "asc" 
                            ? queryable.OrderBy((p, pt, s, c) => p.currentInventory)
                            : queryable.OrderByDescending((p, pt, s, c) => p.currentInventory);
                        break;
                    default: // 默认按创建时间排序
                        queryable = request.OrderDirection?.ToLower() == "asc" 
                            ? queryable.OrderBy((p, pt, s, c) => p.CreateDate)
                            : queryable.OrderByDescending((p, pt, s, c) => p.CreateDate);
                        break;
                }

                // 获取总记录数
                result.TotalCount = await queryable.CountAsync();

                // 计算分页信息
                result.TotalPages = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
                result.PageIndex = request.PageIndex;
                result.PageSize = request.PageSize;
                result.HasPreviousPage = request.PageIndex > 1;
                result.HasNextPage = request.PageIndex < result.TotalPages;

                // 分页查询数据
                var products = await queryable
                    .Select((p, pt, s, c) => new ProductWithDetailsDto
                    {
                        Id = p.Id,
                        GoodsCode = p.goodsCode,
                        GoodsName = p.goodsName,
                        SpecModel = p.specModel,
                        ProductTypeId = p.productTypeId,
                        ProductTypeName = pt.typeName ?? "未分类",
                        SupplierId = p.supplierId,
                        SupplierName = s.SupplierName ?? "未指定供应商",
                        UserId = p.userId,
                        CustomerName = c.CustomerName ?? "未指定客户",
                        PurchasePrice = p.purchasePrice,
                        SalePrice = p.salePrice,
                        CurrentInventory = p.currentInventory,
                        TotalInventoryAmount = p.totalInventoryamount,
                        ShelfLifeManagement = p.shelfLifeManagement,
                        ShelfLife = p.shelfLife,
                        ShelfLifeUnit = p.shelfLifeUnit,
                        WarningDays = p.warningDays,
                        DisplayOrder = p.displayOrder,
                        Status = p.status,
                        Notes = p.notes,
                        Creator = p.Creator,
                        CreateDate = p.CreateDate,
                        Modifier = p.Modifier,
                        ModifyDate = p.ModifyDate
                    })
                    .ToPageListAsync(request.PageIndex, request.PageSize);

                result.Data = products.ToList();
                result.Success = true;
                result.Message = "查询成功";

                return result;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = $"查询失败：{ex.Message}";
                result.Data = new List<ProductWithDetailsDto>();
                return result;
            }
        }
    }
}